<template>
  <div>
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4">
        <el-card body-style="height">
            <el-tree
            :data="departmentData"
            :props="departmentProps"
            :expand-on-click-node="false"
            default-expand-all
            @node-click="handleNodeClick">
          </el-tree>
        </el-card>
      </el-col>
      <el-col :span="20">
        <!--头部操作按钮-->
        <el-row :gutter="10" class="mb8">
          <el-form size="mini" :inline="true" :model="admin" @keyup.enter.native="queryAdminById()">
            <el-form-item label="用户ID">
              <el-input v-model="admin.userId" placeholder="用户ID" clearable></el-input>
            </el-form-item>
            <el-form-item>
              <el-button @click="queryAdminById()">搜索</el-button>
              <el-button type="danger" @click="multipleDeleted" :disabled="multipleSelection.length <= 0">批量修改</el-button>
            </el-form-item>
          </el-form>
        </el-row>
        <!-- 用户表格 -->
        <el-table
          size="mini"
          :data="AdminData"
          border
          @selection-change="handleSelectionChange"
          style="width: 100%;">
          <el-table-column
            type="selection"
            header-align="center"
            align="center"
            width="50">
          </el-table-column>
          <el-table-column
            prop="admin.userId"
            header-align="center"
            align="center"
            width="80"
            label="ID">
          </el-table-column>
          <el-table-column
            prop="admin.username"
            header-align="center"
            align="center"
            label="用户名">
          </el-table-column>
          <el-table-column
            width="80px"
            prop="admin.gender"
            header-align="center"
            align="center"
            label="性别">
            <template slot-scope="scope">
              <el-tag size="small" type="success" v-if="scope.row.admin.gender===1">男</el-tag>
              <el-tag size="small" type="warning" v-else>女</el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="depart"
            header-align="center"
            align="center"
            label="部门">
          </el-table-column>
          <el-table-column
            prop="admin.email"
            header-align="center"
            align="center"
            label="邮箱">
          </el-table-column>
          <el-table-column
            prop="admin.mobile"
            header-align="center"
            align="center"
            label="手机号">
          </el-table-column>
          <el-table-column
            prop="role"
            header-align="center"
            align="center"
            label="角色">
            <template slot-scope="scope">
              <el-tag size="mini" type="danger" v-if="scope.row.role[0]===1">超级管理员</el-tag>
              <el-tag size="mini" type="success" v-if="scope.row.role[1]===5">测试供应商</el-tag>
              <el-tag size="mini" type="success" v-if="scope.row.role[1]===6">测试角色03</el-tag>
              <el-tag size="mini" type="success" v-if="scope.row.role[1]===7">测试角色04</el-tag>
              <el-tag size="mini" type="success" v-if="scope.row.role[1]===8">普通角色</el-tag>
<!--              <el-tag size="mini" type="success" v-else>测试管理员</el-tag>-->
            </template>
          </el-table-column>
          <el-table-column
            prop="admin.status"
            header-align="center"
            align="center"
            label="状态">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.status === 0" size="small" type="danger">禁用</el-tag>
              <el-tag v-else size="small">正常</el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="admin.createTime"
            header-align="center"
            align="center"
            width="180"
            label="创建时间">
          </el-table-column>
          <el-table-column
            fixed="right"
            header-align="center"
            align="center"
            width="130"
            label="操作">
            <template slot-scope="scope">
              <el-button v-if="isAuth('sys:admin:update')" type="text" size="small"
                         @click="addOrUpdateHandle(scope.row.userId)">修改
              </el-button>
              <el-button type="text" size="small" @click="deleteAdmin(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <!--分页样式-->
        <div class="block">
          <span class="demonstration"></span>
          <el-pagination
            layout="total, prev, pager, next, jumper"
            @current-change="currentChangeHandle"
            :current-page=this.currentPage
            :page-size=this.pageSize
            :total=this.total>
          </el-pagination>
        </div>
      </el-col>
    </el-row>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="queryShowAll"></add-or-update>
  </div>
</template>

<script>
import AddOrUpdate from './admin-add-or-update'

export default {
  data () {
    return {
      admin: {
        //根据id查询管理员
        userId: '',
        //根据部门查询管理员
        departmentId: '1'
      },
      departmentProps: {
        children: 'children',
        label: 'name'
      },
      // 所有管理员数据
      AdminData: null,
      //分页数据
      currentPage: 1,
      pageSize: 5,
      total: 0,
      // 部门
      departmentData: null,
      // 选择的数据
      dataListSelections: [],
      addOrUpdateVisible: false,
      //多选获得对象数组
      multipleSelection: [],
      //获得对象数组的id
      multipleId: []
    }
  },
  components: {
    AddOrUpdate
  },
  created () {
    this.queryDepart()
    this.queryShowAll()
  },
  methods: {
    /**
     * 获取所有管理员
     */
    queryShowAll() {
      this.$http({
        url: this.$http.adornUrl('/admin/user/queryShowAll'),
        method: 'get',
        params: this.$http.adornParams({
          'currentPage': this.currentPage,
          'pageSize': this.pageSize
        })
      }).then(({data}) => {
        console.log(data)
        this.AdminData = data.admin
        this.total = data.total
      })
    },

    /**
     * 根据id查询用户
     */
    queryAdminById() {
      if (this.admin.userId === "") {
        alert("请输入用户ID")
        this.queryShowAll()
        return false
      }
      this.$http({
        url: this.$http.adornUrl('/admin/user/queryAdminById'),
        method: 'get',
        params: this.$http.adornParams({
          'userId': this.admin.userId
        })
      }).then(({data}) => {
        console.log(data)
        if(data[0] == null){
          alert("不存在管理员" + "“" + this.admin.userId + "”")
          this.admin.userId=""
          this.queryShowAll();
        }else {
          this.total = 1;
          this.AdminData = data
        }
      })
    },

    /**
     * 获取部门数据列表
     */
    queryDepart() {
      this.$http({
        url: this.$http.adornUrl('/admin/user/queryDepart'),
        method: 'get'
      }).then(({data}) => {
        console.log(data)
        this.departmentData = data
      })
    },

    /**
     * 节点单击事件
     */
    handleNodeClick(row) {
      // console.log(row)
      this.admin.departmentId = row.id
      this.getShowByDepartmentId()
    },

    /**
     * 根据部门id获取管理员列表
     */
    getShowByDepartmentId(){
      this.$http({
        url: this.$http.adornUrl('/admin/user/getShowByDepartmentId'),
        method: 'get',
        params: this.$http.adornParams({
          'departmentId': this.admin.departmentId,
          'currentPage': this.currentPage,
          'pageSize': this.pageSize
        })
      }).then(({data}) => {
        console.log(data)
        this.total = data.total
        this.AdminData = data.admin
      })
    },

    /**
     * 更改当前页面
     */
    currentChangeHandle(val) {
      this.currentPage = val
      if(this.admin.departmentId==="1") {
        this.queryShowAll()
      }else{
        this.getShowByDepartmentId()
      }
    },
    /**
     * 逻辑删除一个
     * @param row
     */
    deleteAdmin(row) {
      this.$http({
        url: this.$http.adornUrl('/admin/user/deleteAdmin'),
        method: 'get',
        params: this.$http.adornParams({
          'userId': row.admin.userId
        })
      }).then(({data}) => {
        this.queryShowAll()
      })
    },
    /**
     * 批量逻辑删除
     * */
    multipleDeleted() {
      console.log(this.multipleId)
      this.$http({
        url: this.$http.adornUrl('/admin/user/multipleDeleted'),
        method: 'post',
        data: this.$http.adornData(this.multipleId, false)
      }).then(({data}) => {
        console.log(data)
        this.queryShowAll()
      })
    },
    /**
     * 获得多选的值
     * */
    handleSelectionChange(val) {
      this.multipleSelection = val;
      /*每次更新多选都重新为空*/
      this.multipleId=[]
      // console.log(this.multipleSelection)
      /*获取选中用户id*/
      for (let i = 0; i < this.multipleSelection.length; i++) {
        // console.log(this.multipleSelection[i])
        this.multipleId.push(this.multipleSelection[i].admin.userId)
      }
      console.log(this.multipleId)
    },
    // 获取要修改管理员的信息
    getAdminInfoById(id) {
      let adminInfo = {}
      if (id !== undefined) {
        this.AdminData.map(item => {
          if (item.userId === id) {
            adminInfo = item
          }
        })
      }
      return adminInfo
    },
    // 新增 / 修改
    addOrUpdateHandle(id) {
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        // 为子组件addOrUpdate传递部门数据
        this.$refs.addOrUpdate.departmentDataTree = this.departmentData
        this.$refs.addOrUpdate.dataFormFromAdmin = this.getAdminInfoById(id)
        this.$refs.addOrUpdate.init(id)
      })
    },
    // 删除
    deleteHandle(row) {
      let userIds
      let username
      if (this.dataListSelections.length >= 1) {
        userIds = this.dataListSelections.map(item => {
          return item.userId
        })
        username = this.dataListSelections.map(item => {
          return item.username
        })
      } else {
        userIds = [row.userId]
        username = [row.username]
      }
      this.$confirm(`确定对[${username.join(',')}]进行[${username.length === 1 ? '删除' : '批量删除'}]操作?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/sys/admin/delete'),
          method: 'post',
          data: this.$http.adornData(userIds, false)
        }).then(({data}) => {
          if (data && data.code === 200) {
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.getDataList()
              }
            })
          } else {
            this.$message.error(data.msg)
          }
        })
      }).catch(() => {
      })
    }
  }
}
</script>
<style scoped>
/deep/ .is-current > .el-tree-node__content {
  background: #F4F6F8;
  position: relative;
}

/deep/ .is-current > .el-tree-node__content::before {
  content: "";
  position: absolute;
  width: 3px;
  height: 100%;
  background: #1989FA;
  top: 0;
  left: 0;;
}
</style>
